//
//  CapitalViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/8/9.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import Moya
import SwiftyJSON
import MJRefresh

class CapitalViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var searchBar: UISearchBar!
    
    var page:Int = 1
    
    var r:JSON = JSON(["operation_time_begin":"", "operation_time_end":"","direction":"","business_type":""])
    
    var datas = [[],[]]
    var dataArray: [JSON] = []
    @objc func openMenu(_ sender: UIBarButtonItem) {
        
        let vc = self.parent as! KYDrawerController
        
        vc.setDrawerState(vc.drawerState == .opened ? .closed : .opened, animated: true)        
    }
    
    @objc func tokenOutOfDate(_ noti:NSNotification) {
        let b = noti.object
        self.r = jsonFormater(data: b as Any)
        self.tableView.mj_header.beginRefreshing()
        let vc = self.parent as! KYDrawerController
        vc.setDrawerState(vc.drawerState == .opened ? .closed : .opened, animated: true)
        self.tableView.mj_header.beginRefreshing()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.tokenOutOfDate(_:)), name: NSNotification.Name.rightRef1, object: nil)

        
        tableView.tableFooterView = UIView()
        tableView.rowHeight = 243
        tableView.register(R.nib.capitalListTableViewCell(), forCellReuseIdentifier: "capitalListTableViewCell")
        self.navigationController?.navigationBar.hideBottomHairline()
        
        let vc = self.parent as! KYDrawerController
        
        vc.navigationItem.title = "资金流水"
        
        vc.drawerDirection = .right
        
        vc.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "fliter_icon"), style: .plain, target: self, action: #selector(self.openMenu(_:)));
        
        loadData()
        
        tableView.mj_header = MJRefreshNormalHeader{ [weak self] in
            self?.page = 1
            self?.loadData()
        }
        
        tableView.mj_footer = MJRefreshAutoFooter {[weak self] in
            
            
            self?.loadData()
            
        }
        
        
        // Do any additional setup after loading the view.
    }
    
    func loadData() {
        
        
        NetWorkRequest(.transactions(operation_time_begin: r["operation_time_begin"].stringValue, operation_time_end: r["operation_time_end"].stringValue, direction: r["direction"].intValue, business_type: r["business_type"].intValue,page: self.page)) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                
                if self.page <= 1 {
                    self.dataArray.removeAll()
                }
                let value = JSON(res as Any)["data"]["data"].arrayValue
                value.forEach({ (json) in
//                    if let dic = json.dictionaryObject, let trans = Transaction(JSON: dic){
                        self.dataArray.append(json)
//                    }
                })
                if value.count <= 0 {
                    self.tableView.mj_footer.isHidden = true
                }else {
                    self.tableView.mj_footer.isHidden = false
                }
                self.tableView.reloadData()
                self.page += 1
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.endRefreshing()
            }
        }
        
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.setValue("取消", forKey: "_cancelButtonText")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "capitalListTableViewCell", for: indexPath) as! CapitalListTableViewCell
        cell.selectionStyle = .none
        cell.model = dataArray[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
